'use strict';

const crypto = require('crypto');
const moment = require('moment');
const uuid = require('uuid');

module.exports.login = async (ctx, next) => {
   try {
      const { models } = ctx.fs.dc;
      const { username, password = '' } = ctx.request.body;
      let password_ = crypto.createHash('md5').update(password).digest('hex');

      let user = await models.User.findOne({
         attributes: { exclude: ['password'] },
         where: {
            username,
            password: password_
         },
         include: [
            { model: models.Department, }
         ]
      })

      if (!user) {
         throw '用户名或密码错误'
      }

      let userInfo = {
         ...user.dataValues,
         authorized: true,
         token: uuid.v4(),
      }

      await models.UserToken.create({
         token: userInfo.token,
         userInfo: userInfo,
         expired: moment().add(3, 'days').toDate()
      })

      ctx.status = 200;
      ctx.body = userInfo
   } catch (error) {
      ctx.logger.log(error)
      ctx.status = 400;
      ctx.body = {
         message: typeof error == 'string' ? error : '登录失败'
      }
   }
}

module.exports.logout = async (ctx, next) => {
   try {
      const { models } = ctx.fs;
      const { header, query } = ctx;
      const token = query.token || header.token;

      await models.UserToken.destroy({
         where: {
            token
         }
      })

      ctx.status = 204;
      ctx.body = {}
   } catch (error) {
      ctx.logger.log(error)
      ctx.status = 400;
      ctx.body = {
         message: ''
      }
   }
}
